<template>
    <n-select :options="options"
              remote
              v-bind="$attrs"
              :consistent-menu-width="false"
              filterable
              placeholder="分类"
              @search="handleSearch"
              :value="props.category?.name||undefined"
              @update:value="handleUpdate"
              :loading="loading"
              size="small"
    ></n-select>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import api from "@/api";

const props = defineProps({
    category: {
        type: Object,
        default: {
            name: '',
            id: '',
        }
    }
})

onMounted(()=>{
    handleSearch('')
})
const emits = defineEmits(['update:category'])
const loading = ref(false)
const options = ref([])
const handleUpdate = (value:any, option:any) => {
    console.log(value)
    emits('update:category',{name:option.name,id:option.id})
}
const handleSearch = (query: string) => {
    loading.value = true
    api.category.queryList({
        pageNo: 1,
        pageSize: 10,
        andParams: JSON.stringify({name: '%' + query + '%'})
    }).then(res => {
        let list = res.data.data.records
        options.value = list.reduce((prev:any, curr:any) => {
            let tmp = {
                label: curr.name,
                value: curr.name,
                id: curr.id,
                name: curr.name,
            };
            if (!prev.some((option:any) => option.value === tmp.value)) {
                prev.push(tmp);
            }
            return prev;
        }, options.value);
    }).finally(() => {
        loading.value = false
    })
}



</script>

<style scoped>

</style>